#!/usr/bin/env python
#
# Copyright 2008 Richard J. Bell. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

""" Main application file for GeoWiki site.

main.py implements a Google app engine geo wiki web site.  It was 
originally developed to support a comunity of users interested in 
America's Great Loop.  It is a personal project supporting my 
interest in doing the Great Loop and to experiment with several 
technologies including: 

    Google appserver
    Django
    Google maps
    YUI
    Javascript
    AJAX
    Python

From a technology perspective it implements a geo wiki.  That is a set of 
wiki pages each of which may have a geographic location or path.

The site provides:
    - A wiki to hold reference information about the Great Loop or other 
      subject
    - Wiki entries may have geo locations, paths, etc
    - Entries with geo locations can be displayed on a google map
    - All entries are viewable in a list format
    - Wiki entries have comments
    - Anyone can view the entire site
    - Users can register
    - Registered users can add and edit wiki pages
    - Provisions for displaying NOAA raster and enc charts as a google map 
      mashup
"""

__version__ = '$Revision 0.1$'
__author__  = "Richard Bell <rbell01824@earthlink.net>"
__date__ = 'Dec 12, 2008'
__credits__ = """
Various portions of this code and site are derived from open sources
including:
            The geodatastore example, see http://code.google.com/p/geodatastore/ and
                http://code.google.com/p/geodatastore/
            The Google app engine code lab, 
                see http://code.google.com/p/google-app-engine-codelab/
            YUI examples from several sources including:
                http://blog.davglass.com/2006/06/yui-code-samples/
                http://www.satyam.com.ar/yui/
"""
#===========================================================================
"""
MODS:
20081212 - Start initial development
20090118 - Create new project repository at http://code.google.com/p/appspot-geowiki
20090324 - Beta release as version 7.626

fixme: add default content pages

"""

# Python Imports
import wsgiref.handlers
import os
import logging

# Google App Engine Imports
from google.appengine.ext import webapp

# Application Imports
from app.gwbaserequesthandler import GWRequestHandler
from app import gwadminhandlers
from app import gwpage
from app import gwuser

class NotFound( GWRequestHandler ):
    """ Handles all urls not otherwise handled """
    def get( self, page = 'admin/notfound.html' ):
        self.generate( 'admin/notfound.html', templateValues={ 'title': 'Page Not Found', 'wikiTitle': page } )
        return
        
class HomePage( GWRequestHandler ):
    """ Handles '/' requests """
    def get( self ):
        self.redirect( '/Great_Loop_Home' )
        return
    
class Test0( GWRequestHandler ):
    """ Supports development testing.
        /gw/test0?page=abc&foo=lkjlkjlkjlj
    """
    def get( self ):
        page = self.request.get('page')
        foo = self.request.get('foo')
        logging.info('-----> <<%s>> <<%s>>' % ( page, foo))
        self.generate( 'test0.html', templateValues={ 'title': 'Test 0'} )
        return
class Test1( GWRequestHandler ):
    """ Supports development testing. """
    def get( self ):
        logging.info( 'hi dude' )
        from app import gwpage
        q = gwpage.GWPage.all()
        tags = ['FL', 'faq']
        q = q.filter( 'tags IN', tags )
        for r in q:
            logging.info('>>> %s', r.wikiTitle )
        return
class Test2( GWRequestHandler ):
    """ Supports development testing. """
    def get( self ):
        self.generate( 'test2.html', templateValues={ 'title': 'Test 2' } )
        return
    
class UnderConstruction(GWRequestHandler):
    def get(self, pagename):
        self.generate( 'admin/underconstruction.html', templateValues={ 'pagename': pagename } )
    
_URLS = [
         ('/gw/test0', Test0 ),                                                 # various test things
         ('/gw/test1', Test1 ),                                                 # various test things
         ('/gw/test2', Test2 ),                                                 # various test things
         
         ('/gw/map', gwpage.GWMap ),                                            # display map and features
         ('/gw/pageserver', gwpage.GWPageServer ),                              # page server operations (get page, save page, etc.)
         
         ('/underconstruction/([^/]+)', UnderConstruction ),                    # display under construction page
         
         ('/gw/developer', gwadminhandlers.Developer ),                         # display developer erase/load data page
         ('/gw/json/developer', gwadminhandlers.DeveloperJson ),                # execute developer erase/load data
         
         ('/gw/login', gwuser.UserLogin),                                       # geowiki login
         ('/gw/login2', gwuser.UserLogin2),                                     # geowiki login 2, updates the last login time
         ('/gw/logout', gwuser.UserLogout),                                     # geowiki logout
         
         ('/gw/admin/tags', gwadminhandlers.TagsEdit),                          # display HTML admin add/edit/delete list of feature tags
         ('/gw/json/tags', gwadminhandlers.TagsJSON),                           # get/post json list of feature tags page
         
         ('/gw/admin/colors', gwadminhandlers.ColorsEdit),                      # display HTML admin add/edit/delete colors page
         ('/gw/json/colors', gwadminhandlers.ColorsJSON),                       # get/post json list of colors
         
         ('/gw/admin/markers', gwadminhandlers.MarkersEdit),                    # display HTML admin markers page
         ('/gw/json/markers', gwadminhandlers.MarkersList),                     # get list of markers
         ('/gw/json/marker', gwadminhandlers.Markers),                          # post marker (server decides on marker name)
         ('/gw/json/marker/([^/]+)', gwadminhandlers.Markers),                  # get marker, delete marker
         
         ('/gw/admin/users', gwuser.UsersEdit),                                 # display HTML admin users page
         ('/gw/json/users', gwuser.UsersList),                                  # get list of users
         ('/gw/json/user/([^/]+)', gwuser.Users),                               # get user, post user, delete user
         
         ('/gw/list', gwpage.GWPageList),                                       # display HTML list of GW pages
         ('/gw/json/pages', gwpage.GWPagesJson),                                # get json list of pages
         
         ('/gw/newpage/([^/]+)', gwpage.GWPageEdit),                            # display HTML page edit screen
         ('/gw/editpage/([^/]+)', gwpage.GWPageEdit),                           # display HTML page edit screen
         ('/gw/json/page/([^/]+)', gwpage.GWPageJson),                          # save the specified page
         
         ('/([^/]+)', gwpage.GWPageView),                                       # display view HTML the page
         ('/', HomePage),                                                       # display our home page
         ('/(.*)', NotFound)                                                    # display not found
         ]

def main():
    from app.gwconfig import DEBUG
    application = webapp.WSGIApplication(_URLS, debug=DEBUG)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
